﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;


namespace Hongapo_Common
{
   public class ImageHelper
   {


       #region 以文件方式保存图片
       /// <summary>
        /// 
        /// </summary>
        /// <param name="fileurl">原图URL</param>
        /// <param name="minwidth">缩略图宽</param>
        /// <param name="minheight">缩略图高</param>
        /// <param name="FilePath">上传到“”文件夹下目录(文件夹名)</param>
        /// <param name="filename">原图文件名</param>
        /// <returns></returns>
        public static void SendToSmallImage(string fileurl, int minwidth, int minheight, string FilePath, string filename)
        {
            try
            {
                System.Drawing.Image img = System.Drawing.Image.FromFile(fileurl);
                int lenEnd = fileurl.LastIndexOf('.');
                string fileType = fileurl.Substring(lenEnd, fileurl.Length - lenEnd);


                ImageFormat imgformat = img.RawFormat;

                Size newSize = NewSize(minwidth, minheight, img.Width, img.Height);

                Bitmap bm = new Bitmap(newSize.Width, newSize.Height);
                Graphics g = Graphics.FromImage(bm);

                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                g.Dispose();

                // 以下代码为保存图片时，设置压缩质量
                EncoderParameters encoderParams = new EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 75;

                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;

                //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICI = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[x];//设置JPEG编码
                        break;
                    }
                }

                string stringpath =FilePath+filename;
                string imagename = filename;
                try
                {
                    //MemoryStream ms = new MemoryStream();
                    //bm.Save(ms, jpegICI, encoderParams);// 保存文件流
                    bm.Save(stringpath, jpegICI, encoderParams); // 保存到文件
                }
                catch (Exception e)
                {
                    LogHelper.WriteLog(e);
                }
                finally
                {
                    img.Dispose();
                    bm.Dispose();


                }
                //return imagename;
            }
            catch (Exception ex)
            {

                LogHelper.WriteLog(ex);
            }


        }


       #endregion

       #region 以流的方式保存图片
        /// <summary>
        ///  高质量图片压缩 
        /// </summary>
        /// <param name="Stream">文件流</param>
        /// <param name="minwidth">缩略图宽</param>
        /// <param name="minheight">缩略图高</param>
        /// <param name="FilePath">上传到“”文件夹下目录(文件夹名)</param>
        /// <param name="filename">原图文件名</param>
        /// <returns></returns>
        public static void SendToSmallImage(Stream stream, int minwidth, int minheight, string FilePath, string filename)
        {
            try
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                string fileType = ".jpg";
                ImageFormat imgformat = img.RawFormat;

                Size newSize = NewSize(minwidth, minheight, img.Width, img.Height);

                Bitmap bm = new Bitmap(newSize.Width, newSize.Height);
                Graphics g = Graphics.FromImage(bm);

                // 设置画布的描绘质量
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                g.Dispose();

                // 以下代码为保存图片时，设置压缩质量
                EncoderParameters encoderParams = new EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 94;

                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;

                //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICI = null;

                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[x];//设置JPEG编码
                        break;
                    }
                }

                string stringpath = FilePath+filename;
                string imagename = filename;
                try
                {
                    MemoryStream ms = new MemoryStream();
                    bm.Save(ms, jpegICI, encoderParams);// 保存文件流
                    //bm.Save(stringpath, jpegICI, encoderParams); // 保存到文件
                    //EBusiness.Utils.FTPHelper.Upload(ms, FilePath, filename);
                    ms.Close();
                    //bm.Save(stringpath,allICI, encoderParams); // 保存到文件
                    byte[] bytes = ms.ToArray();
                    using (FileStream fs = new FileStream(stringpath, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Close();
                    }
                    ms.Close();
                   
                }
                catch (Exception e)
                {
                    LogHelper.WriteLog(e);
                }
                finally
                {
                    img.Dispose();
                    bm.Dispose();
                }

            }
            catch (Exception ex)
            {

                LogHelper.WriteLog(ex);
            }
        }

        #endregion

       #region 缩放尺寸
        /// <summary>
        ///
        /// </summary>
        /// <param name="minwidth">微缩图要设置的宽度</param>
        /// <param name="minheight">微缩图要设置的长度</param>
        /// <param name="forwidth">原图宽度</param>
        /// <param name="forheight">原图长度</param>
        /// <returns></returns>
        private static System.Drawing.Size NewSize(int minwidth, int minheight, int forwidth, int forheight)
        {
            int newwidth;
            int newheight;
            if (forwidth > forheight)
            {
                newwidth = minwidth;
                newheight = newwidth * forheight / forwidth;
            }
            else
            {
                newheight = minheight;
                newwidth = newheight * forwidth / forheight;
            }
            System.Drawing.Size _Size = new Size();
            _Size.Height = newheight;
            _Size.Width = newwidth;
            return _Size;
        }
        #endregion

       #region 创建文件夹
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static bool CreateFolder(string Path)
        {
            try
            {
                if (!System.IO.Directory.Exists(Path))
                {
                    System.IO.Directory.CreateDirectory(Path);
                }
                return true;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(ex.Message);
                return false;
            }
        }
       #endregion

       #region 删除文件
        public static bool DeleteFile(string filePath)
        {
            try
            {
                
                if (File.Exists(filePath))
                {
                    FileInfo fi = new FileInfo(filePath);
                    fi.Attributes = FileAttributes.Normal;
                    File.Delete(filePath);
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
                return false;
            }


        }
       #endregion

       #region 判断文件是否存在
        public static bool ExistsFile(string filePath)
        {

            if (System.IO.File.Exists(filePath))
            {

                return true;

            }

            return false;

        }
       #endregion

   }
}
